const Event = require('../models/Event');
const NotificationService = require('./notification');

class EventService {
  // 获取事件详情
  static async getEventDetails(eventId) {
    try {
      const event = await Event.getById(eventId);
      if (!event) {
        throw new Error('事件不存在');
      }
      return event;
    } catch (error) {
      throw error;
    }
  }
  
  // 创建新事件
  static async createEvent(title, description, severity) {
    try {
      if (!title || !severity) {
        throw new Error('标题和严重性不能为空');
      }
      
      const eventId = await Event.create(title, description, severity);
      const event = await this.getEventDetails(eventId);
      
      // 发送新事件通知
      NotificationService.sendNewEventNotification(event);
      
      return event;
    } catch (error) {
      throw error;
    }
  }
  
  // 确认事件
  static async acknowledgeEvent(eventId, userId) {
    try {
      // 获取当前事件状态
      const event = await Event.getById(eventId);
      if (!event) {
        throw new Error('事件不存在');
      }
      
      if (event.status !== 'pending') {
        throw new Error('事件状态不允许确认');
      }
      
      // 更新事件状态
      const changes = await Event.acknowledge(eventId, userId);
      if (changes === 0) {
        throw new Error('事件确认失败');
      }
      
      // 获取更新后的事件
      const updatedEvent = await this.getEventDetails(eventId);
      
      // 发送通知
      NotificationService.sendEventUpdate(updatedEvent);
      
      return updatedEvent;
    } catch (error) {
      throw error;
    }
  }
  
  // 解决事件
  static async resolveEvent(eventId, userId) {
    try {
      // 获取当前事件状态
      const event = await Event.getById(eventId);
      if (!event) {
        throw new Error('事件不存在');
      }
      
      if (event.status === 'resolved') {
        throw new Error('事件已解决');
      }
      
      // 更新事件状态
      const changes = await Event.resolve(eventId, userId);
      if (changes === 0) {
        throw new Error('事件解决失败');
      }
      
      // 获取更新后的事件
      const updatedEvent = await this.getEventDetails(eventId);
      
      // 发送通知
      NotificationService.sendEventUpdate(updatedEvent);
      
      return updatedEvent;
    } catch (error) {
      throw error;
    }
  }
  
  // 获取待处理事件
  static async getPendingEvents() {
    try {
      return await Event.getPending();
    } catch (error) {
      throw error;
    }
  }
}

module.exports = EventService;